package 多线程.交替输出;

import java.util.concurrent.*;
import java.util.concurrent.locks.LockSupport;

/**
 * @author : K k
 * @date : 11:30 2020/8/11
 * 自旋锁  两个状态循环切换
 * 线程占用cpu不放，消耗cpu性能,不经由操作系统即 不用通过用户态转向内核态进行访问内存和物理设备
 * 内核态：系统调用（程序主动调用，申请转变内核态），异常和外围设备中断（后两者被动）
 * 适用于代码量小的
 * 与重量级锁区别 并发量高时候用
 */
public class Ans4CASEnum {

    enum ReadyToRun {T1, T2}

    static volatile ReadyToRun r = ReadyToRun.T1;

    public static void main(String[] args) {
        char[] a1 = "1234567".toCharArray();
        char[] a2 = "ABCDEFG".toCharArray();

        new Thread(() -> {
            for (char c : a1) {
                while (r != ReadyToRun.T1) {} //线程竞争失败，while循环阻塞自己
                System.out.println(c);
                r=ReadyToRun.T2;
            }
        }).start();

        new Thread(() -> {
            for (char c : a2) {
                while (r != ReadyToRun.T2) {}
                System.out.println(c);
                r=ReadyToRun.T1;
            }
        }).start();

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<String> hello = executorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("执行方法");
                return "hello";
            }
        });

        try {
            System.out.println(hello.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.exit(1);
    }
}
